package org.teremail;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

import org.teremail.delivery.Exchange;
import org.teremail.service.ServiceManagerMBean;
import org.teremail.service.ServiceRegistrar;

import com.google.inject.Guice;
import com.google.inject.Injector;

public class ServerSingleton {

    private final static FutureTask<ServerSingleton> instance = 
        new FutureTask<ServerSingleton>(new Callable<ServerSingleton>() {
            public ServerSingleton call() throws Exception {
                ServerSingleton s = new  ServerSingleton();
                s.startAll();
                return s;
            }
        });
    
    private final Injector injector;
    
    private ServerSingleton() {
        injector = Guice.createInjector(Main.SMTP);
    }

    private void startAll() {
        ServiceManagerMBean serviceManager = injector.getInstance(ServiceRegistrar.class).createServiceManager();
        serviceManager.startAll();
        serviceManager.bindAll();
    }
    
    public static ServerSingleton getInstance() {
        instance.run();
        try {
            return instance.get();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Server failed to start", e);
        }
    }
    
    public Exchange getExchange() {
        return injector.getInstance(Exchange.class);
    }
}
